﻿using System;
using Apollo;
using System.Linq;
using Apollo.Web;
using System.Collections;
using System.Collections.Generic;
using System.Web;

namespace Apollo.Website
{
    public partial class MasterPage : System.Web.UI.MasterPage
    {
        protected int selectedUserViewId = -1;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            if ((this.Page.User.Identity as User) != null && (this.Page.User.Identity as User).LastLoginDate < new DateTime(2011, 10, 13))
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();

            this.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

            if (!this.IsPostBack)
                PopulateMenus();
        }

        protected void PopulateMenus()
        {
            int selectedMenuItemId = 0;
            int selectedRootMenuItemId = 0;

            if ((this.Page as IApolloPage) != null)
            {
                selectedMenuItemId = (this.Page as IApolloPage).SelectedMenuItemID;
                selectedRootMenuItemId = (this.Page as IApolloPage).SelectedRootMenuItemId;
            }
            else if (!string.IsNullOrEmpty(this.Request["MenuId"]))
            {
                if (int.TryParse(this.Request["MenuId"], out selectedMenuItemId))
                {
                    MenuItem selected = Apollo.Application.Meta<MenuItem>()
                        .SingleOrDefault<MenuItem>(m => m.Id == selectedMenuItemId);

                    if (selected != null)
                    {
                        if (selected.Parent == null)
                            selectedRootMenuItemId = selectedMenuItemId;
                        else
                        {
                            MenuItem parent = selected.Parent;

                            while (parent != null)
                            {
                                selectedRootMenuItemId = parent.Id;
                                parent = parent.Parent;
                            }
                        }
                    }
                    else
                        selectedMenuItemId = 0;
                }
            }

            if (!int.TryParse(this.Request["UserViewId"], out selectedUserViewId))
            {
                selectedUserViewId = -1;
            }

            PopulateTopMenu(selectedRootMenuItemId);

            PopulateLeftMenu(selectedRootMenuItemId, selectedMenuItemId);
        }

        protected void PopulateTopMenu(int selectedRootMenuItemId)
        {
            foreach (MenuItem mi in Apollo.Application.Meta<MenuItem>()
                                        .Where<MenuItem>(m => m.Parent == null)
                                        .OrderBy<MenuItem, int>(m => m.DisplayOrder))
            {
                if (!mi.IsAllowed())
                    continue;

                LanguageDefinition ld = Apollo.Application.Meta<LanguageDefinition>()
                    .SingleOrDefault<LanguageDefinition>(l => l.Type == "MenuItem"
                        && l.CodeHi == mi.Id.ToString()
                        && l.Language.Id == Apollo.Application.CurrentLanguage.Id);

                LiteralTopMenu.Text += string.Format(
                    "\n<li class=\"{3}\"><a href=\"{2}\"><img src=\"{1}\" border=\"0\" /> {0}</a>"
                    , new object[] {
                ld != null ? ld.DisplayName : mi.Name
                , string.IsNullOrEmpty(mi.IconPath) ? "css/icons/icon_01.png" : mi.IconPath
                , string.IsNullOrEmpty(mi.NavigateUrl) ? "View.aspx?MenuId=" + mi.Id.ToString() : mi.NavigateUrl
                , mi.Id == selectedRootMenuItemId ? "memu-root ui-state-default" : "memu-root"
            });


                IEnumerable<MenuItem> subItems = Apollo.Application.Meta<MenuItem>()
                                        .Where<MenuItem>(m => m.Parent != null && m.Parent.Id == mi.Id)
                                        .OrderBy<MenuItem, int>(m => m.DisplayOrder);

                if (mi.Id == selectedRootMenuItemId)
                    continue;

                this.PopulateTopMenuSubItems(subItems);


                LiteralTopMenu.Text += "</li>";

            }
        }

        protected void PopulateTopMenuSubItems(IEnumerable<MenuItem> subItems)
        {
            if (subItems != null && subItems.Count<MenuItem>() > 0)
            {
                LiteralTopMenu.Text += "\n\t<ul>";

                foreach (MenuItem smi in subItems)
                {
                    if (!smi.IsAllowed())
                        continue;

                    LanguageDefinition sld = Apollo.Application.Meta<LanguageDefinition>()
                            .SingleOrDefault<LanguageDefinition>(l => l.Type == "MenuItem"
                                && l.CodeHi == smi.Id.ToString()
                                && l.Language.Id == Apollo.Application.CurrentLanguage.Id);

                    // subsubitems
                    IEnumerable<MenuItem> subsubItems = Apollo.Application.Meta<MenuItem>()
                                        .Where<MenuItem>(m => m.Parent != null && m.Parent.Id == smi.Id)
                                        .OrderBy<MenuItem, int>(m => m.DisplayOrder);

                    LiteralTopMenu.Text += string.Format(
                        "\n\t\t<li class=\"{3}\"><a href=\"{2}\"><img src=\"{1}\" border=\"0\" /> {0}</a>"
                        , new object[] {
                                sld != null ? sld.DisplayName : smi.Name
                                , string.IsNullOrEmpty(smi.IconPath) ? "css/icons/icon_01.png" : smi.IconPath
                                , string.IsNullOrEmpty(smi.NavigateUrl) ? "View.aspx?MenuId=" + smi.Id.ToString() : smi.NavigateUrl
                                , ((subsubItems != null && subsubItems.Count() > 0) ? "has-children" : "")
                            });

                    
                    this.PopulateTopMenuSubItems(subsubItems);

                    LiteralTopMenu.Text += "\n\t\t</li>";
                }

                LiteralTopMenu.Text += "\n\t</ul>";
            }
        }

        protected void PopulateLeftMenu(int selectedRootMenuItemId, int selectedMenuItemId)
        {
            foreach (MenuItem mi in Apollo.Application.Meta<MenuItem>()
                                        .Where<MenuItem>(m => m.Parent != null
                                            && m.Parent.Id == selectedRootMenuItemId)
                                        .OrderBy<MenuItem, int>(m => m.DisplayOrder))
            {
                LiteralLeftMenu.Text += GetListItemString(mi, selectedMenuItemId, true);
            }
        }

        protected string GetListItemString(MenuItem mi, int selectedId, bool includeSubitems)
        {
            if (!mi.IsAllowed())
                return "";

            string listItemString = "";

            string url = mi.NavigateUrl ?? "";

            if (mi.EntityView != null)
                url = "View.aspx?MenuId=" + mi.Id.ToString();

            LanguageDefinition ld = Apollo.Application.Meta<LanguageDefinition>()
                .SingleOrDefault<LanguageDefinition>(l => l.Type == "MenuItem"
                    && l.CodeHi == mi.Id.ToString()
                    && l.Language.Id == Apollo.Application.CurrentLanguage.Id);

            listItemString = string.Format(
                "<li><a href=\"{2}\" class=\"{3}\"><img src=\"{1}\" border=\"0\" /> {0}</a>"
                , new object[] {
                ld != null ? ld.DisplayName : mi.Name
                , string.IsNullOrEmpty(mi.IconPath) ? "css/icons/icon_01.png" : mi.IconPath
                , url
                , mi.Id == selectedId ? "ui-state-default" : ""
            });

            if (includeSubitems)
            {
                IEnumerable<MenuItem> subItems = Apollo.Application.Meta<MenuItem>()
                                        .Where<MenuItem>(m => m.Parent != null && m.Parent.Id == mi.Id)
                                        .OrderBy<MenuItem, int>(m => m.DisplayOrder);

                if (subItems != null && subItems.Count<MenuItem>() > 0)
                {
                    listItemString += "<ul>";

                    foreach (MenuItem submi in subItems)
                        listItemString += GetListItemString(submi, selectedId, includeSubitems);

                    listItemString += "</ul>";
                }

                // include userviews
                if (Apollo.Application.CurrentUserViews != null)
                {
                    IEnumerable<UserView> userViews = Apollo.Application.CurrentUserViews
                                            .Where<UserView>(uv => uv.MenuItem != null && uv.MenuItem.Id == mi.Id);



                    if (userViews != null && userViews.Count() > 0)
                    {
                        listItemString += "<ul>";

                        foreach (UserView userView in userViews)
                            listItemString += string.Format(
                                "<li><a href=\"{2}\" class=\"{3}\"><img src=\"{1}\" border=\"0\" /> {0}</a>"
                                , new object[] {
                                userView.Name
                            ,   string.IsNullOrEmpty(mi.IconPath) ? "css/icons/icon_01.png" : mi.IconPath
                            ,   string.Format("View.aspx?MenuId={0}&UserViewId={1}", mi.Id, userView.Id)
                            ,   userView.Id == selectedUserViewId ? "ui-state-default" : ""
                        });

                        listItemString += "</ul>";
                    }
                }
            }

            listItemString += "</li>";

            return listItemString;
        }

    }
}